package org.xiaov.lunasql.engine.function;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLReplaceable;
import com.alibaba.druid.sql.ast.expr.*;

import java.util.List;

/**
 * <p>
 * InsertFunc
 * </p>
 *
 * @author LunaSQL
 * @since 2024/12/15 23:06
 */
public class InsertFunc implements MySqlFunction {
    private final static String METHOD_NAME = "insert";

    @Override
    public boolean accept(SQLMethodInvokeExpr methodInvokeExpr) {
        return METHOD_NAME.equalsIgnoreCase(methodInvokeExpr.getMethodName());
    }

    @Override
    public void transform(SQLMethodInvokeExpr methodInvokeExpr) {
        List<SQLExpr> arguments = methodInvokeExpr.getArguments();
        SQLExpr sqlExpr = arguments.get(0);
        SQLIntegerExpr point = (SQLIntegerExpr) arguments.get(1);
        SQLIntegerExpr length = (SQLIntegerExpr) arguments.get(2);
        SQLCharExpr newStr = (SQLCharExpr) arguments.get(3);
        String substr = "SUBSTR";
        SQLMethodInvokeExpr method1 = new SQLMethodInvokeExpr(substr, null, sqlExpr, new SQLIntegerExpr(1), new SQLIntegerExpr(point.getNumber().intValue() - 1));
        SQLMethodInvokeExpr method2 = new SQLMethodInvokeExpr(substr, null, sqlExpr, new SQLIntegerExpr(point.getNumber().intValue() + length.getNumber().intValue()));
        SQLBinaryOpExpr sqlBinaryOpExpr = new SQLBinaryOpExpr(new SQLBinaryOpExpr(method1, SQLBinaryOperator.Concat, newStr), SQLBinaryOperator.Concat, method2);
        if (methodInvokeExpr.getParent() instanceof SQLReplaceable repeatable) {
            repeatable.replace(methodInvokeExpr, sqlBinaryOpExpr);
        }
    }
}
